package com.vf.admin.client.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppDynamicDao;
import com.vf.admin.client.dao.AppUserDao;
import com.vf.admin.client.service.AppBeckoningService;
import com.vf.admin.client.service.AppDynamicService;
import com.vf.admin.client.service.LovelyGodLogService;
import com.vf.admin.client.service.MessageChatFromService;
import com.vf.admin.client.tx.utils.TxIm;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.fiwork.util.StringUtil;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.utils.StringEx;
import com.vf.admin.utils.aliyunoss.OssCheckUtils;
import org.apache.hadoop.mapred.IFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AppDynamicServiceImpl implements AppDynamicService {

    @Autowired
    AppDynamicDao appDynamicDao;
    @Autowired
    AppUserDao appUserDao;
    @Autowired
    LovelyGodLogService lovelyGodLogService;
    @Autowired
    AppBeckoningService appBeckoningService;
    @Autowired
    MessageChatFromService messageChatFromService;
    @Autowired
    RedisUtil redisUtil;


    @Override
    public void saveOrUpdate(AppDynamic appDynamic) {
        appDynamicDao.save(appDynamic);
    }

    @Override
    public void dongtaiSave(String message, String images, String lon, String lat, String city, Integer userid, String pic, String nick, String phone, Integer sex, Integer type) {
        AppDynamic dynamic = new AppDynamic();
        dynamic.setMessage(message);
        dynamic.setImage(images);
        dynamic.setCreatetime(new Date());
        dynamic.setUserid(userid);
        dynamic.setPic(pic);
        dynamic.setSex(sex);
        dynamic.setPhone(phone);
        dynamic.setNick(nick);
        if (!StringEx.isNull(lat)) {
            dynamic.setLat(lat);
        } else {
            dynamic.setLat("");
        }
        if (!StringEx.isNull(lon)) {
            dynamic.setLon(lon);
        } else {
            dynamic.setLon("");
        }
        if (!StringEx.isNull(city)) {
            dynamic.setCity(city);
        } else {
            dynamic.setCity("");
        }
        dynamic.setGivenum(0);
        dynamic.setCommentnum(0);
        dynamic.setStatus(2);  //设置删除不显示状态
        dynamic.setType(type);
        appDynamicDao.save(dynamic);
        //缓存到redis
        if (ObjectUtil.isNotEmpty(type)) {
            if (type.equals(1)) {
                //保存redis鉴黄
                String keyId = String.format(RedisKeys.GREEN_IMAGE, dynamic.getId());
                redisUtil.set(keyId, images,300);
            }
            if (type.equals(2)) {
                //保存redis鉴黄
                String keyId = String.format(RedisKeys.GREEN_VIEDO, dynamic.getId());
                redisUtil.set(keyId, images,3600);
            }
        }
    }

    @Override
    public AppDynamic getByid(Integer id) {
        return appDynamicDao.get(id);
    }

    @Override
    public List<AppDynamic> specificUserList(Integer userid, SplitPageBean splitPageBean) {
        List<AppDynamic> appDynamics = appDynamicDao.specificUserList(userid, splitPageBean);
        if (appDynamics == null) {
            return new ArrayList<>();
        }
        return appDynamics;
    }

    @Override
    public List<AppDynamic> selectPage(HashMap<String, Object> hashMap, SplitPageBean splitPageBean) {
        return appDynamicDao.selectPage(hashMap, splitPageBean);
    }

    @Override
    public List<AppDynamic> selectNearbyPage(Map<String, Object> params, SplitPageBean splitPageBean) {
        return appDynamicDao.selectNearbyPage(params, splitPageBean);
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        appDynamicDao.updateStatus(id, status);
    }

    @Override
    public void dianzanNumUpdate(Integer id, Integer status) {
        appDynamicDao.dianzanNumUpdate(id, status);
    }

    @Override
    public void pinglunNumUpdate(Integer id, Integer status) {
        appDynamicDao.pinglunNumUpdate(id, status);
    }

    @Override
    public void delDongtai(Integer id) {
        appDynamicDao.delDongtai(id);
    }

    @Override
    public void zhuanfaUpdate(Integer id) {
        appDynamicDao.zhuanfaUpdate(id);
    }

    @Override
    public List<AppDynamic> list(Map<String, Object> params) {
        return appDynamicDao.list(params);
    }

    @Override
    public List<String> myDynamicPic(Integer userId) {
        List<String> list = new ArrayList<>();
        List<AppDynamic> appDynamics = appDynamicDao.myDynamic(userId);
        for (AppDynamic d : appDynamics) {
            if (!StringUtil.isNullOrEmpty(d.getImage())) {
                String[] split = d.getImage().split(",");
                for (int i = 0; i < split.length; i++) {
                    list.add(split[i]);
                }
            }
        }
        return list;
    }

    /**
     * 双方为异性 如果双方没有爱神牵线、没有心动记录、没有聊天记录发送对话框消息
     *
     * @param fromUser
     * @param user
     * @param dynamicId
     * @param dynamicFirstImage
     */
    public void sendDynamicHello(AppUser fromUser, AppUser user, Integer dynamicId, String dynamicFirstImage, String text) {
        if (fromUser.getSex() != user.getSex()) {
            LovelyGodLog lovelyGodLog = lovelyGodLogService.getLimitOne(fromUser.getId(), user.getId());
            if (lovelyGodLog == null) {
                AppBeckoning beckoning = appBeckoningService.getLimitOne(fromUser.getId(), user.getId());
                if (beckoning == null) {
                    MessageChatFrom messageChatFrom = messageChatFromService.get(fromUser.getId(), user.getId());
                    if (messageChatFrom == null) {
                        //给异性点赞和评论时 绑定聊天主被关系 男方扣费
                        if (fromUser.getSex() == 1) {
                            messageChatFromService.add(fromUser.getId(), user.getId());
                        } else if (user.getSex() == 1) {
                            messageChatFromService.add(user.getId(), fromUser.getId());
                        }
                        TxIm.sendDynamicHello(user.getTengxuncode(), fromUser.getTengxuncode(), text, dynamicId, dynamicFirstImage);
                    }
                }
            }
        }
    }

    @Override
    public boolean updateDynamic(List<String> userIdList,  String time, String address) {
        //时间取出最大值最小值
        String[] split1 = time.split("-");
        Arrays.sort(split1);
        String max; //最大
        String min; //最小
        max = split1[1];
        min = split1[0];
        //获取用户userId
        userIdList.forEach(e -> {
            //查出该用户所有朋友圈
            List<AppDynamic> appDynamics = appDynamicDao.myDynamic(Integer.valueOf(e));
            if (ObjectUtil.isNotEmpty(appDynamics) && appDynamics.size() > 0) {

                //临时时间常量
                Date tempTime = new Date();

                for (int i = 0; i < appDynamics.size(); i++) {
                    if (i == 0) {
                        //如果是第一条不执行修改操作
                        AppDynamic appDynamic = appDynamics.get(i);
                        //临时保存
                        tempTime.setTime(appDynamic.getCreatetime().getTime());
                    } else {
                        //取出地址
//                        String[] split2 = address.split(",");
//                        Random random = new Random();
//                        int aInt = random.nextInt(split2.length);
//                        String addressString = split2[aInt];
//                        System.out.println(addressString);
                        AppDynamic appDynamic = appDynamics.get(i);
                        //取出时间随机数
                        int day = (int) (Integer.parseInt(min) + Math.random() * (Integer.parseInt(max) - Integer.parseInt(min) + 1));
                        System.out.println(day);
                        //生成插入时间
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        Calendar rightNow = Calendar.getInstance();
                        System.out.println("数据库时间"+sdf.format(tempTime));
                        rightNow.setTime(tempTime);
                        //减少或者增加几天
                        rightNow.add(Calendar.DATE, -day);
                        String format = sdf.format(rightNow.getTime());
                        System.out.println("插入的时间"+format);
                        tempTime.setTime(rightNow.getTime().getTime());

                        appDynamic.setCreatetime(rightNow.getTime());
//                        appDynamic.setCity(addressString);
                        appDynamicDao.save(appDynamic);
                    }
                }
            }

        });

        return true;
    }

    @Override
    public boolean updateDongTaiNow(List<String> userIdList) {

        userIdList.forEach(e->{

            //查出该用户所有朋友圈
            List<AppDynamic> appDynamics = appDynamicDao.myDynamic(Integer.valueOf(e));
            //取最后一条
            if (ObjectUtil.isNotEmpty(appDynamics)){
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Date start = null;
                try {
                    start = format.parse("2023-08-01 00:22:22");
                } catch (ParseException parseException) {
                    parseException.printStackTrace();
                }
                Date end = null;
                try {
                    end = format.parse("2023-08-09 00:22:22");
                } catch (ParseException parseException) {
                    parseException.printStackTrace();
                }

                long date = random(start.getTime(),end.getTime());
                Date date1 = new Date(date);
                AppDynamic appDynamic = appDynamics.get(appDynamics.size() - 1);
                AppDynamic appDynamic1 = new AppDynamic();
                appDynamic1.setId(appDynamic.getId());
                appDynamic1.setCreatetime(date1);
                appDynamicDao.save(appDynamic1);
            }
        });
        return true;
    }

    private static long random(long begin,long end){
        long rtn = begin + (long)(Math.random() * (end - begin));
        if(rtn == begin || rtn == end){
            return random(begin,end);
        }
        return rtn;
    }

}
